package com.brsanthu.sgwidgets.client;

import java.util.Date;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.smartgwt.client.core.Rectangle;
import com.smartgwt.client.widgets.form.fields.FormItemIcon;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.IconClickEvent;
import com.smartgwt.client.widgets.form.fields.events.IconClickHandler;

@SuppressWarnings("synthetic-access")
public class DateTimeFormItem extends TextItem {

    private static DateTimeFormat dfDateTime = DateTimeFormat.getFormat("yyyy/MM/dd h:m:s a");

    private DateTimeChooser datetimeChooser = null;

    public DateTimeFormItem(JavaScriptObject jsObj) {
        super(jsObj);
        init();
    }

    public DateTimeFormItem(String name, String title) {
        super(name, ClientUtils.bold(title));
        init();
    }

    public DateTimeFormItem(String name) {
        super(name);
        init();
    }

    public DateTimeFormItem() {
        init();
    }

    private void init() {
        FormItemIcon formItemIcon = new FormItemIcon();
        formItemIcon.setSrc("calendar.png");
        setIcons(formItemIcon);

        addIconClickHandler(new IconClickHandler() {
            @Override
            public void onIconClick(IconClickEvent event) {
                Rectangle iconRect = getIconPageRect(event.getIcon());
                showDialog(iconRect.getLeft(), iconRect.getTop());
            }
        });

        datetimeChooser = new DateTimeChooser();
        datetimeChooser.addCallbackHandler(new CallbackHandler() {
            @Override
            public void handle(Object object) {
                setValueAsDate((Date) object);
            }
        });
    }

    public Date getValueAsDate() {

        String dateString = (String) getValue();
        if (ClientUtils.isEmpty(dateString)) {
            return null;
        }

        return dfDateTime.parse(dateString);
    }

    public void setValueAsDate(Date date) {
        setValue(dfDateTime.format(date));
    }

    private void showDialog(int left, int top) {

        Date date = null;
        if (((String) getValue()) == null) {
            date = new Date();
        } else {
            date = dfDateTime.parse((String) getValue());
        }

        datetimeChooser.setData(date);
        datetimeChooser.show();
        datetimeChooser.moveTo(left, top);
    }
}
